/**
 * WebConfig - 企微后台 API 配置
 */
import { success, failed } from '@gnlab/utils'
import { useStreams } from '@/lib/utils'
import services from '@/services'
import { getRecentExternals, getExternalRelation } from '@/services/contact-types/externals/api'
import { type QywxAPIConfig } from '@/services/features/web-config'
import { getQywxs } from '@/services/qywxs'

export type { QywxAPIConfig }

export function useAPIConfigs() {
  const [webConfig] = useStreams(services.features.webConfig.data)
  const apiConfigs = useMemo(
    () => webConfig.qywxAPIConfigs.filter(v => v.corpId), // 忽略没有 corpId 的主体
    [webConfig.qywxAPIConfigs],
  )
  const load = useCallback(async () => services.features.webConfig.load(), [])
  return {
    apiConfigs,
    loadApiConfigs: load,
  }
}

/**
 * 添加/修改配置
 *
 * 传入 prevCorpId 代表修改
 * （corpId 是主键，但它本身也可能被修改，所以需要提供修改前的作为参照）
 */
export async function updateApiConfig(config: QywxAPIConfig, prevCorpId?: string) {
  const webConfig = services.features.webConfig.data.value
  const updated = [...webConfig.qywxAPIConfigs]

  if (prevCorpId === undefined) {
    if (updated.find(v => v.corpId === config.corpId))
      return failed(`corpId ${config.corpId} 已存在`)
    updated.push({ ...config })
  } else {
    const index = updated.findIndex(v => v.corpId === prevCorpId)
    if (index === -1) return failed(`corpId ${prevCorpId} 不存在`)
    updated[index] = { ...config }
  }

  return services.features.webConfig.update({
    ...webConfig,
    qywxAPIConfigs: updated,
  })
}

/**
 * 删除配置
 */
export async function removeApiConfig(corpId: string) {
  const webConfig = services.features.webConfig.data.value
  const updated = webConfig.qywxAPIConfigs.filter(v => v.corpId !== corpId)
  return services.features.webConfig.update({
    ...webConfig,
    qywxAPIConfigs: updated,
  })
}

/**
 * 确认配置是否有效
 */
export async function confirmApiConfig(corpIdOrigin: string) {
  const qywxsRes = await getQywxs('', true)
  if (!qywxsRes.success) return qywxsRes
  const wxids = qywxsRes.data.filter(v => v.corp_id === corpIdOrigin).map(v => v.wx_id)
  if (!wxids.length) return failed('需登录此主体下的企业微信，且企微下有客户，才能完成检查')

  const contactsRes = await getRecentExternals({ wxids, page: 1, pageSize: 1 })
  if (!contactsRes.success) return contactsRes
  const contact = contactsRes.data[0]
  if (!contact) return failed('需登录此主体下的企业微信，且企微下有客户，才能完成检查')

  const relationRes = await getExternalRelation({
    ownerWxid: contact.ownerWxid,
    contactUserId: contact.userId,
  })
  if (!relationRes.success) return relationRes
  if (!relationRes.data.externalUserId && !relationRes.data.unionId)
    return failed('获取客户资料失败，请确认 CorpId 和 Secret 是否正确')

  return success()
}
